package com.cryann.mqttserver.mqttProcess.mqttMsgHandler;

import com.cryann.mqttserver.exception.MqttException;
import com.google.common.collect.ImmutableSet;
import io.netty.handler.codec.mqtt.*;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @author cRyann
 * @date 2018/12/28 0028 15:33
 * @description:
 */
@Component
public class MQTT_2$3$1_1 extends AbstractMqttHandler {
    @Override
    protected Set<MqttMessageType> handlerType() {
        return ImmutableSet.of(MqttMessageType.SUBSCRIBE,
                MqttMessageType.UNSUBSCRIBE,
                MqttMessageType.PUBLISH);
    }

    @Override
    protected boolean checkMsg(MqttMessage request) {
        if ( request instanceof MqttPublishMessage ) {
            MqttPublishVariableHeader variableHeader = (MqttPublishVariableHeader) request.variableHeader();
            if ( MqttQoS.AT_MOST_ONCE.value() < request.fixedHeader().qosLevel().value() && variableHeader.packetId() == 0 ) {
                throw new MqttException("[MQTT-2.3.1-1]  PUBLISH（QoS 大于 0）控制报文必须包含一个非零的 16 位报文标识符（Packet Identifier。");
            }
        } else {
            MqttMessageIdVariableHeader variableHeader = (MqttMessageIdVariableHeader) request.variableHeader();
            if ( MqttQoS.AT_MOST_ONCE.value() < request.fixedHeader().qosLevel().value() && variableHeader.messageId() == 0 ) {
                throw new MqttException("[MQTT-2.3.1-1] SUBSCRIBE，UNSUBSCRIBE（QoS 大于 0）控制报文必须包含一个非零的 16 位报文标识符（Packet Identifier。");
            }
        }

        return true;
    }
}
